<script setup name="Calculator">
import { ref, watch, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { calculateProperty } from '@/api/product/mdtk'

const { t } = useI18n()
const router = useRouter()

// 响应式数据
const propertyType = ref('surfaceTension')
const calcType = ref('binary')
const temperature = ref(1573)
const composition = ref({
	binary: { x1: 0.5 },
	ternary: { x1: 0.33, x2: 0.33, x3: 0.34 },
})
const selectedSystem = ref({
	surfaceTension: { binary: 'Mg_Al', ternary: 'Mg_Al_Zn' },
	viscosity: { binary: 'Mg_Al', ternary: 'Mg_Al_Si' },
	thermalConductivity: { binary: '', ternary: '' },
})
const result = ref(null)
const isLoading = ref(false)
const error = ref(null)

// 系统选项
const systemOptions = {
	surfaceTension: {
		binary: [
			{ value: 'Mg_Al', label: 'Mg_Al' },
			{ value: 'Mg_La', label: 'Mg_La' },
			{ value: 'Mg_Ce', label: 'Mg_Ce' },
			{ value: 'Mg_Gd', label: 'Mg_Gd' },
			{ value: 'Mg_Y', label: 'Mg_Y' },
			{ value: 'Mg_Nd', label: 'Mg_Nd' },
			{ value: 'Al_La', label: 'Al_La' },
			{ value: 'Al_Ce', label: 'Al_Ce' },
			{ value: 'Al_Gd', label: 'Al_Gd' },
			{ value: 'Al_Y', label: 'Al_Y' },
			{ value: 'Al_Nd', label: 'Al_Nd' },
			{ value: 'Mg_Zn', label: 'Mg_Zn' },
			{ value: 'Al_Zn', label: 'Al_Zn' },
			{ value: 'Zn_La', label: 'Zn_La' },
			{ value: 'Zn_Ce', label: 'Zn_Ce' },
			{ value: 'Zn_Gd', label: 'Zn_Gd' },
			{ value: 'Zn_Y', label: 'Zn_Y' },
			{ value: 'Zn_Nd', label: 'Zn_Nd' },
		],
		ternary: [
			{ value: 'Mg_Al_Zn', label: 'Mg_Al_Zn' },
			{ value: 'Mg_Al_La', label: 'Mg_Al_La' },
			{ value: 'Mg_Al_Ce', label: 'Mg_Al_Ce' },
			{ value: 'Mg_Al_Gd', label: 'Mg_Al_Gd' },
			{ value: 'Mg_Al_Y', label: 'Mg_Al_Y' },
			{ value: 'Mg_Al_Nd', label: 'Mg_Al_Nd' },
			{ value: 'Mg_Zn_La', label: 'Mg_Zn_La' },
			{ value: 'Mg_Zn_Ce', label: 'Mg_Zn_Ce' },
			{ value: 'Mg_Zn_Gd', label: 'Mg_Zn_Gd' },
			{ value: 'Mg_Zn_Y', label: 'Mg_Zn_Y' },
			{ value: 'Mg_Zn_Nd', label: 'Mg_Zn_Nd' },
			{ value: 'Al_Zn_La', label: 'Al_Zn_La' },
			{ value: 'Al_Zn_Ce', label: 'Al_Zn_Ce' },
			{ value: 'Al_Zn_Gd', label: 'Al_Zn_Gd' },
			{ value: 'Al_Zn_Y', label: 'Al_Zn_Y' },
			{ value: 'Al_Zn_Nd', label: 'Al_Zn_Nd' },
		],
	},
	viscosity: {
		binary: [
			{ value: 'Mg_Al', label: 'Mg_Al' },
			{ value: 'Al_Si', label: 'Al_Si' },
			{ value: 'Al_Cu', label: 'Al_Cu' },
			{ value: 'Al_Fe', label: 'Al_Fe' },
			{ value: 'Mg_Si', label: 'Mg_Si' },
			{ value: 'Mg_Cu', label: 'Mg_Cu' },
			{ value: 'Mg_Fe', label: 'Mg_Fe' },
			{ value: 'Si_Cu', label: 'Si_Cu' },
			{ value: 'Si_Fe', label: 'Si_Fe' },
			{ value: 'Fe_Cu', label: 'Fe_Cu' },
		],
		ternary: [
			{ value: 'Mg_Al_Si', label: 'Mg_Al_Si' },
			{ value: 'Mg_Al_Cu', label: 'Mg_Al_Cu' },
			{ value: 'Mg_Al_Fe', label: 'Mg_Al_Fe' },
			{ value: 'Al_Si_Cu', label: 'Al_Si_Cu' },
			{ value: 'Al_Si_Fe', label: 'Al_Si_Fe' },
		],
	},
	thermalConductivity: {
		binary: [],
		ternary: [],
	},
}

// 验证输入
const validateInputs = () => {
	error.value = null

	// 验证温度
	if (isNaN(temperature.value) || temperature.value <= 0) {
		error.value = t('calculator.messages.invalidTemperature')
		return false
	}

	// 验证组分
	if (calcType.value === 'binary') {
		const x1 = composition.value.binary.x1
		if (isNaN(x1) || x1 < 0 || x1 > 1) {
			error.value = t('calculator.messages.invalidComposition')
			return false
		}
	} else {
		const { x1, x2, x3 } = composition.value.ternary
		if (
			isNaN(x1) ||
			isNaN(x2) ||
			isNaN(x3) ||
			x1 < 0 ||
			x1 > 1 ||
			x2 < 0 ||
			x2 > 1 ||
			x3 < 0 ||
			x3 > 1
		) {
			error.value = t('calculator.messages.invalidComposition')
			return false
		}

		const sum = x1 + x2 + x3
		if (Math.abs(sum - 1) > 0.0001) {
			error.value = t('calculator.messages.compositionSumError')
			return false
		}
	}

	return true
}

// 计算函数
const calculate = async () => {
	if (!validateInputs()) {
		return
	}

	isLoading.value = true
	result.value = null
	error.value = null

	try {
		// 准备请求数据
		const requestData = {
			temperature: temperature.value,
			system_type: calcType.value,
			system: selectedSystem.value[propertyType.value][calcType.value],
			composition:
				calcType.value === 'binary'
					? [composition.value.binary.x1, 1 - composition.value.binary.x1]
					: [
							composition.value.ternary.x1,
							composition.value.ternary.x2,
							composition.value.ternary.x3,
						],
		}

		// 使用新的API接口
		const response = await calculateProperty(propertyType.value, requestData)

		if (response.success) {
			result.value = {
				value: response.result,
				unit:
					propertyType.value === 'surfaceTension'
						? t('calculator.results.units.surfaceTension')
						: t('calculator.results.units.viscosity'),
				propertyName:
					propertyType.value === 'surfaceTension'
						? t('calculator.results.surfaceTension')
						: t('calculator.results.viscosity'),
			}

			// 滚动到结果区域
			await nextTick()
			const resultsElement = document.querySelector('.result-section')
			if (resultsElement) {
				resultsElement.scrollIntoView({
					behavior: 'smooth',
					block: 'center',
				})
			}
		} else {
			throw new Error(
				response.message || t('calculator.messages.calculationFailed')
			)
		}
	} catch (err) {
		error.value = err.message || t('calculator.messages.calculationFailed')
		console.error('计算错误:', err)
	} finally {
		isLoading.value = false
	}
}

// 当属性类型或计算类型变化时重置结果
watch([propertyType, calcType], () => {
	result.value = null
	error.value = null
})

const onChange = () => {
	if (propertyType.value === 'thermalConductivity') {
		window.open('/Product/Conductivity', '_blank')
		propertyType.value = 'surfaceTension'
	}
}

onMounted(() => {
	nextTick(() => {})
})
</script>

<template>
	<main class="calculator-page">
		<div class="container">
			<!-- 页面标题 -->
			<div class="page-header">
				<h1 class="page-title">{{ t('calculator.title') }}</h1>
				<p class="page-subtitle">
					{{ t('calculator.subtitle') }}
				</p>
				<div class="title-divider"></div>
			</div>

			<div class="main-content">
				<!-- 参数输入卡片 -->
				<div class="card">
					<h2>
						<span>⚙️</span>
						<span>{{ t('calculator.inputParams.title') }}</span>
					</h2>

					<!-- 计算类型选择 -->
					<div class="form-group">
						<label for="propertyType"
							>{{ t('calculator.inputParams.propertyType') }}:</label
						>
						<select id="propertyType" v-model="propertyType" @change="onChange">
							<option value="surfaceTension">
								{{ t('calculator.inputParams.propertyTypes.surfaceTension') }}
							</option>
							<option value="viscosity">
								{{ t('calculator.inputParams.propertyTypes.viscosity') }}
							</option>
							<option value="thermalConductivity">
								{{
									t('calculator.inputParams.propertyTypes.thermalConductivity')
								}}
							</option>
						</select>
					</div>

					<!-- 组元数选择 -->
					<div class="form-group">
						<label for="calcType"
							>{{ t('calculator.inputParams.calcType') }}:</label
						>
						<select id="calcType" v-model="calcType">
							<option value="binary">
								{{ t('calculator.inputParams.calcTypes.binary') }}
							</option>
							<option value="ternary">
								{{ t('calculator.inputParams.calcTypes.ternary') }}
							</option>
						</select>
					</div>

					<!-- 温度输入 -->
					<div class="form-group">
						<label for="tempInput"
							>{{ t('calculator.inputParams.temperature') }}:</label
						>
						<input
							type="number"
							id="tempInput"
							v-model.number="temperature"
							:placeholder="t('calculator.inputParams.temperaturePlaceholder')"
							step="0.1"
						/>
					</div>

					<!-- 系统选择 -->
					<div class="form-group">
						<label for="systemSelect">
							{{
								calcType === 'binary'
									? t('calculator.inputParams.binarySystem')
									: t('calculator.inputParams.ternarySystem')
							}}:
						</label>
						<select
							id="systemSelect"
							v-model="selectedSystem[propertyType][calcType]"
						>
							<option
								v-for="option in systemOptions[propertyType][calcType]"
								:key="option.value"
								:value="option.value"
							>
								{{ option.label }}
							</option>
						</select>
					</div>

					<!-- 组分输入 -->
					<div class="form-group">
						<label>{{ t('calculator.inputParams.composition') }}:</label>
						<div class="composition-section">
							<div v-if="calcType === 'binary'" class="composition-input">
								<div class="composition-item">
									<input
										type="number"
										step="0.01"
										v-model.number="composition.binary.x1"
										placeholder="0.5"
										min="0"
										max="1"
									/>
									<label>{{
										t('calculator.inputParams.compositionBinary.x1')
									}}</label>
								</div>
								<div class="composition-item">
									<input
										type="number"
										:value="(1 - composition.binary.x1).toFixed(3)"
										readonly
									/>
									<label>{{
										t('calculator.inputParams.compositionBinary.x2')
									}}</label>
								</div>
							</div>
							<div v-else class="composition-input">
								<div class="composition-item">
									<input
										type="number"
										step="0.01"
										v-model.number="composition.ternary.x1"
										placeholder="0.33"
										min="0"
										max="1"
									/>
									<label>{{
										t('calculator.inputParams.compositionTernary.x1')
									}}</label>
								</div>
								<div class="composition-item">
									<input
										type="number"
										step="0.01"
										v-model.number="composition.ternary.x2"
										placeholder="0.33"
										min="0"
										max="1"
									/>
									<label>{{
										t('calculator.inputParams.compositionTernary.x2')
									}}</label>
								</div>
								<div class="composition-item">
									<input
										type="number"
										step="0.01"
										v-model.number="composition.ternary.x3"
										placeholder="0.34"
										min="0"
										max="1"
									/>
									<label>{{
										t('calculator.inputParams.compositionTernary.x3')
									}}</label>
								</div>
							</div>
						</div>
					</div>

					<!-- 错误显示 -->
					<div v-if="error" class="message-area">
						<div class="error-message">
							{{ error }}
						</div>
					</div>
				</div>

				<!-- 操作和提示卡片 -->
				<div class="card">
					<h2>
						<span>🎯</span>
						<span>{{ t('calculator.operationPanel.title') }}</span>
					</h2>

					<!-- 计算按钮 -->
					<button
						class="calculate-button"
						:disabled="isLoading"
						@click="calculate"
					>
						<div class="loading-spinner" :class="{ show: isLoading }"></div>
						🔬
						{{
							isLoading
								? t('calculator.button.calculating')
								: t('calculator.button.calculate')
						}}
					</button>

					<div class="tips-section">
						<h4>💡 {{ t('calculator.tips.title') }}</h4>
						<ul class="tips-list">
							<li>{{ t('calculator.tips.tip1') }}</li>
							<li>{{ t('calculator.tips.tip2') }}</li>
							<li>{{ t('calculator.tips.tip3') }}</li>
							<li>{{ t('calculator.tips.tip4') }}</li>
						</ul>
					</div>
				</div>
			</div>

			<!-- 结果展示区域 -->
			<div v-if="result" class="card result-section">
				<h2>
					<span>📊</span>
					<span>{{ t('calculator.results.title') }}</span>
				</h2>

				<div class="result-display">
					<div class="result-card">
						<h3>{{ result.propertyName }}</h3>
						<div class="result-value">{{ result.value.toFixed(3) }}</div>
						<div class="result-unit">{{ result.unit }}</div>
					</div>
				</div>

				<div class="result-info">
					<p class="result-description">
						<strong>{{ t('calculator.results.calcInfo') }}:</strong><br />
						{{ t('calculator.results.temperature') }}: {{ temperature }} K<br />
						{{ t('calculator.results.system') }}:
						{{ selectedSystem[propertyType][calcType] }}<br />
						{{ t('calculator.results.type') }}:
						{{
							calcType === 'binary'
								? t('calculator.inputParams.calcTypes.binary')
								: t('calculator.inputParams.calcTypes.ternary')
						}}
					</p>
				</div>
			</div>
		</div>
	</main>
</template>

<style scoped lang="scss">
@import url('@/styles/content/index.scss');
@import url('@/styles/content/components/calculator.scss');

.calculator-page {
	min-height: 100vh;
	background: var(--theme-content-bg);
	color: var(--theme-content-text);
	padding: 80px 0;

	.container {
		max-width: 1200px;
		margin: 0 auto;
		padding: 0 20px;
	}

	.page-header {
		text-align: center;
		margin-bottom: 40px;

		.page-title {
			font-size: 3rem;
			font-weight: 700;
			background: var(--theme-gradient-title);
			-webkit-background-clip: text;
			-webkit-text-fill-color: transparent;
			background-clip: text;
			margin-bottom: 10px;
		}

		.page-subtitle {
			font-size: 1.2rem;
			color: var(--theme-content-text-muted);
			margin-bottom: 20px;
		}

		.title-divider {
			height: 2px;
			width: 100px;
			background: var(--theme-gradient-title);
			margin: 20px auto;
			border-radius: 1px;
		}
	}

	.main-content {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 30px;
		margin-bottom: 20px;
	}

	.card {
		background: var(--theme-card-bg);
		border: 1px solid var(--theme-card-border);
		border-radius: 16px;
		padding: 30px;
		box-shadow: var(--theme-card-shadow);
		backdrop-filter: var(--backdrop-blur);
		transition: all 0.3s ease;

		&:hover {
			transform: translateY(-2px);
			box-shadow: var(--theme-card-shadow-hover);
		}

		h2 {
			font-size: 1.5rem;
			margin-bottom: 25px;
			color: var(--theme-accent);
			display: flex;
			align-items: center;
			gap: 10px;
		}
	}

	.form-group {
		margin-bottom: 20px;

		label {
			display: block;
			margin-bottom: 8px;
			font-weight: 500;
			color: var(--theme-content-text);
		}

		input,
		select {
			width: 100%;
			padding: 12px 16px;
			border: 1px solid var(--theme-input-border);
			border-radius: 8px;
			font-size: 16px;
			background: var(--theme-input-bg);
			color: var(--theme-input-text);
			transition: all 0.3s ease;

			&:focus {
				outline: none;
				border-color: var(--theme-accent);
				box-shadow: 0 0 0 3px rgba(100, 181, 246, 0.1);
			}

			&::placeholder {
				color: var(--theme-input-placeholder);
			}

			&:read-only {
				background: var(--theme-section-alt-bg);
				cursor: default;
			}
		}
	}

	.composition-section {
		margin-top: 10px;
	}

	.composition-input {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 15px;

		.composition-item {
			display: flex;
			flex-direction: column;

			input {
				margin-bottom: 8px;
			}

			label {
				font-size: 14px;
				text-align: center;
				color: var(--theme-content-text-muted);
				margin: 0;
			}
		}
	}

	.calculate-button {
		width: 100%;
		padding: 16px;
		background: var(--theme-gradient-primary);
		border: none;
		border-radius: 12px;
		color: white;
		font-size: 18px;
		font-weight: 600;
		cursor: default;
		transition: all 0.3s ease;
		margin-top: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10px;
		box-shadow: 0 4px 15px rgba(100, 181, 246, 0.3);

		&:hover:not(:disabled) {
			transform: translateY(-2px);
			box-shadow: var(--theme-button-shadow-hover);
		}

		&:disabled {
			opacity: 0.6;
			cursor: not-allowed;
			transform: none;
		}

		.loading-spinner {
			display: none;
			width: 20px;
			height: 20px;
			border: 2px solid transparent;
			border-top: 2px solid white;
			border-radius: 50%;
			animation: spin 1s linear infinite;

			&.show {
				display: inline-block;
			}
		}
	}

	.form-actions {
		display: flex;
		justify-content: space-between;
		gap: 1rem;
		margin-bottom: 1.5rem;

		.back-button,
		.reset-button {
			flex: 1;
			padding: 0.75rem 1.5rem;
			border: 2px solid var(--theme-accent);
			border-radius: 8px;
			background: transparent;
			color: var(--theme-accent);
			font-weight: 600;
			cursor: pointer;
			transition: all 0.3s ease;

			&:hover {
				background: var(--theme-accent);
				color: white;
				transform: translateY(-2px);
			}
		}

		.reset-button {
			border-color: var(--theme-warning);
			color: var(--theme-warning);

			&:hover {
				background: var(--theme-warning);
				color: white;
			}
		}
	}

	.tips-section {
		padding: 15px;
		background: var(--theme-tips-bg);
		border-radius: 8px;
		border: 1px solid var(--theme-content-border);

		h4 {
			color: var(--theme-accent);
			margin-bottom: 10px;
		}

		.tips-list {
			padding-left: 20px;
			margin: 0;
			list-style-type: '• ';

			li {
				margin-bottom: 5px;
				font-size: 14px;
				color: var(--theme-content-text-muted);
				line-height: 1.6;
			}
		}
	}

	.message-area {
		margin-top: 15px;

		.error-message {
			background: var(--theme-error-bg);
			border: 1px solid var(--theme-error-border);
			color: var(--theme-error-text);
			padding: 12px;
			border-radius: 8px;
			font-size: 14px;
		}
	}

	.result-section {
		grid-column: 1 / -1;
		margin-top: 20px;

		.result-display {
			display: flex;
			justify-content: center;
			margin-bottom: 30px;

			.result-card {
				background: var(--theme-gradient-result);
				border-radius: 16px;
				padding: 30px;
				text-align: center;
				border: 1px solid var(--theme-accent);
				min-width: 250px;

				h3 {
					color: var(--theme-content-title);
					margin-bottom: 15px;
					font-size: 1.3rem;
				}

				.result-value {
					font-size: 2.5rem;
					font-weight: 700;
					color: var(--theme-accent);
					margin: 15px 0;
				}

				.result-unit {
					font-size: 1.1rem;
					color: var(--theme-content-text-muted);
				}
			}
		}

		.result-info {
			background: var(--theme-section-alt-bg);
			border-radius: 12px;
			padding: 20px;
			border: 1px solid var(--theme-content-border);

			.result-description {
				margin: 0;
				font-size: 14px;
				line-height: 1.6;
				color: var(--theme-content-text-muted);
			}
		}
	}
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}
	100% {
		transform: rotate(360deg);
	}
}

// 响应式设计
@media (max-width: 768px) {
	.calculator-page {
		padding: 60px 0;

		.container {
			padding: 0 15px;
		}

		.page-header {
			.page-title {
				font-size: 2rem;
			}

			.page-subtitle {
				font-size: 1rem;
			}
		}

		.main-content {
			grid-template-columns: 1fr;
		}

		.composition-input {
			grid-template-columns: 1fr;
		}
	}
}
</style>
